package com.tmt.im.manager.handler;

import com.fasterxml.jackson.annotation.JsonProperty;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.context.request.WebRequest;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description TODO
 * @Author wuyi
 * @Date 2024/9/12 14:06
 * @Version 1.0
 **/
@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseEntity<Map<String, Object>> handleValidationExceptions(MethodArgumentNotValidException ex, WebRequest request) {
        Map<String, Object> body = new HashMap<>();
        body.put("code", HttpStatus.BAD_REQUEST.value());
        body.put("msg", HttpStatus.BAD_REQUEST.getReasonPhrase());
        body.put("data", getErrorMessages(ex.getBindingResult().getTarget(), ex.getBindingResult().getFieldErrors()));
        return new ResponseEntity<>(body, HttpStatus.BAD_REQUEST);
    }

    private Map<String, String> getErrorMessages(Object target, List<FieldError> fieldErrors) {
        Map<String, String> errorMessages = new HashMap<>();
        for (FieldError error : fieldErrors) {
            String fieldName = error.getField();
            if (target != null){
                try {
                    Field field = target.getClass().getDeclaredField(fieldName);
                    JsonProperty ann = field.getAnnotation(JsonProperty.class);
                    fieldName = ann.value();
                }catch (Exception ex){
                }
            }
            errorMessages.put(fieldName, error.getDefaultMessage());
        }
        return errorMessages;
    }
}